"""
分类相关序列化器
"""

from rest_framework import serializers
from pecco_site.models import Category, CategoryTranslation


class CategoryTranslationSerializer(serializers.ModelSerializer):
    """分类翻译序列化器"""
    class Meta:
        model = CategoryTranslation
        fields = ['locale', 'name', 'description']


class CategoryListSerializer(serializers.ModelSerializer):
    """分类列表序列化器"""
    translations = CategoryTranslationSerializer(many=True, read_only=True)
    icon_url = serializers.SerializerMethodField()

    class Meta:
        model = Category
        fields = [
            'id', 'slug', 'icon_url', 'sort_order',
            'is_active', 'created_at', 'updated_at', 'translations'
        ]

    def get_icon_url(self, obj):
        if obj.icon:
            request = self.context.get('request')
            if request:
                return request.build_absolute_uri(obj.icon.url)
            return obj.icon.url
        return None


class CategoryDetailSerializer(serializers.ModelSerializer):
    """分类详情序列化器"""
    translations = CategoryTranslationSerializer(many=True, required=False)
    icon_url = serializers.SerializerMethodField()

    class Meta:
        model = Category
        fields = [
            'id', 'slug', 'icon', 'icon_url', 'sort_order',
            'is_active', 'created_at', 'updated_at', 'translations'
        ]

    def get_icon_url(self, obj):
        if obj.icon:
            request = self.context.get('request')
            if request:
                return request.build_absolute_uri(obj.icon.url)
            return obj.icon.url
        return None

    def create(self, validated_data):
        translations_data = validated_data.pop('translations', [])
        category = Category.objects.create(**validated_data)

        for translation_data in translations_data:
            CategoryTranslation.objects.create(category=category, **translation_data)

        return category

    def update(self, instance, validated_data):
        translations_data = validated_data.pop('translations', None)

        # 更新分类基本信息
        for attr, value in validated_data.items():
            setattr(instance, attr, value)
        instance.save()

        # 更新翻译
        if translations_data is not None:
            # 删除现有翻译
            instance.translations.all().delete()
            # 创建新翻译
            for translation_data in translations_data:
                CategoryTranslation.objects.create(category=instance, **translation_data)

        return instance

